import type { ArtColumn } from 'ali-react-table';
import { Button, Tooltip } from 'antd';
import _ from 'lodash';

const marketList = [
  {
    label: '新疆电力交易中心',
    value: 'PXBXJ',
  },
];

const dimensionOptions: any[] = ['区域', '风电场', '时间'];

const dimensionValus: any = {
  区域: 'regionId',
  风电场: 'wfName',
  时间: 'date',
};

const accountListColumns = ({
  edit,
  del,
}: {
  edit: (row: any) => void;
  del: (id: string) => void;
}): ArtColumn[] => {
  return [
    {
      name: '风电场名称',
      code: 'wfName',
      align: 'center',
      render: (value, row) => {
        return row.isMaintained === '1' ? (
          <Tooltip title="自有场站">
            <span className="is-maintained">{value}</span>
          </Tooltip>
        ) : (
          value
        );
      },
    },
    { name: '装机容量（MW）', code: 'wfCapacity', align: 'center' },
    { name: '账号', code: 'account', align: 'center' },
    { name: '密码', code: 'password', align: 'center' },
    {
      name: '操作',
      code: 'opt',
      align: 'center',
      render: (value, row) => {
        return (
          <>
            <Button type="link" onClick={() => edit(row)}>
              编辑
            </Button>
            <Button type="link" onClick={() => del(row.id)}>
              删除
            </Button>
          </>
        );
      },
    },
  ];
};

const buildTableData = (data: any, head: string[], isMaintained: string[]) => {
  const columns: ArtColumn[] = [
    {
      name: '聚合纬度',
      code: 'latitude',
      align: 'center',
      lock: true,
      width: 180,
      features: { tree: true },
      render: (value) => {
        return isMaintained.indexOf(value) > -1 ? (
          <Tooltip title="自有场站">
            <span className="is-maintained">{value}</span>
          </Tooltip>
        ) : (
          value
        );
      },
    },
  ];
  let dataSource: any[] = [];
  const filterOption: any = {};
  const chartDatas: any = {};

  const recursion = (obj: any, parentKey?: string) => {
    const result: any[] = [];
    const entries = sortObj(obj);

    for (const [key, value] of entries) {
      const pKey = parentKey ? parentKey : 'first';
      if (filterOption[pKey]) {
        filterOption[pKey].push({
          label: key,
          value: key,
        });
      } else {
        filterOption[pKey] = [];
        filterOption[pKey].push({
          label: key,
          value: key,
        });
      }

      if (typeof value === 'object' && !Array.isArray(value)) {
        result.push({
          latitude: key,
          children: recursion(value, key),
          id: _.uniqueId(),
        });
      } else if (Array.isArray(value)) {
        const lastObj: any = { latitude: key, id: _.uniqueId() };
        value.forEach((val, index) => {
          const chartsKeys = `${parentKey}-${key}`;
          chartDatas[chartsKeys] = chartDatas[chartsKeys] ? chartDatas[chartsKeys] : [];
          chartDatas[chartsKeys].push(val !== '-' ? val : 0);

          const cKey = head[index];
          lastObj[cKey] = val;
          columns.push({
            name: cKey,
            code: cKey,
            align: 'center',
            width: 150,
          });
        });
        result.push(lastObj);
      }
    }
    return result;
  };

  if (data && Object.keys(data).length > 0) {
    dataSource = recursion(data);
  }

  return {
    columns: _.uniqBy(columns, 'code'),
    dataSource,
    filterOption,
    chartDatas,
  };
};

const buildChartOptions = (filterOption: any, chartDatas: any) => {
  let listVal: string[] = [];
  const first = filterOption.first;
  if (first && first.length > 0) {
    const firstVal = first[0].value;
    listVal = [firstVal, ...findOptionsByKey(firstVal, filterOption)];
  }
  return listVal;
};

const findOptionsByKey = (key: string, filterOption: any) => {
  const afterKeys: string[] = [];
  const recursion = (parentKey: string) => {
    if (filterOption[parentKey]) {
      const first = filterOption[parentKey][0];
      afterKeys.push(first.value);
      recursion(first.value);
    }
  };

  recursion(key);
  return afterKeys;
};

const findCurrentChartKeys = (keys: string[]): string => {
  let key = '';
  if (keys.length > 1) {
    key = `${keys[keys.length - 2]}-${keys[keys.length - 1]}`;
  }
  return key;
};

const buildExportData = (dataSource: any[]) => {
  const exportData: any[] = [];
  const recursion = (list: any[]) => {
    for (let i = 0; i < list.length; i++) {
      exportData.push(list[i]);
      if (list[i].children && list[i].children.length > 0) {
        recursion(list[i].children);
      }
    }
  };
  recursion(dataSource);
  return exportData;
};

const sortObj = (obj: any) => {
  return Object.entries(obj).sort(([a], [b]) => {
    if (a < b) return -1;
    if (a > b) return 1;
    return 0;
  });
};

export {
  marketList,
  dimensionOptions,
  dimensionValus,
  accountListColumns,
  buildTableData,
  buildChartOptions,
  findCurrentChartKeys,
  findOptionsByKey,
  buildExportData,
  sortObj,
};
